package day1129_2;

import java.sql.*;

public class G1 {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Connection conn=getConnection();//1.用下边的方法获取链接
        PreparedStatement  ps=conn.prepareStatement(
                "select*from stu");//2.sql发送给Mysql，且预编译
        ResultSet rs=ps.executeQuery();//3.执行SQL
        while(rs.next()){//4.从ResultSet获取查询结果
            System.out.println(rs.getString(1));
            System.out.println(rs.getString(2));
        }   //                从rs中获取表格中的第2列数据
        tl.set(conn);//5.将连接对象存入到ThreadLocal中
    }

    //米缸     <米>
    //ThreadLocal<可以存储Connection>
    static ThreadLocal<Connection>   tl=new ThreadLocal<>();
    public static   Connection  getConnection() throws ClassNotFoundException, SQLException {//获取数据库连接
        Connection  conn=tl.get();//1.从tl中获取链接对象(米缸幺米)
        if(conn==null){//2.如果没有获取到连接就在if中建立连接存入tl
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/big2?serverTimezone=GMT%2B8&useSSL=false",
                    "root","root");//2.//2.
            tl.set(conn);
        }
        return   conn;//2.如果获取到连接了就返回连接
    }

}







